package com.feri.ssm.controller;

import com.feri.ssm.entity.Pet;
import com.feri.ssm.service.intf.PetService;
import com.feri.ssm.vo.PageVo;
import com.feri.ssm.vo.R;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/api/project/")
public class PetController {
    @Resource
    private PetService service;

    //新增操作
    @PostMapping("add.do")
    public R add(Pet pet){
        return service.save(pet);
    }

    //删除操作
    @PostMapping("del.do")
    public R del(int id){
        return service.del(id);
    }

    //修改操作
    @PostMapping("update.do")
    public R update(Pet pet){
        return service.update(pet);
    }

    //查询操作
    @RequestMapping("selectAll.do")
    public PageVo selectAll(int page, int limit){
        return service.selectAll(page, limit);
    }

    //查询操作
    @RequestMapping("selectById2.do")
    public PageVo selectById2(String name, String msgName, Integer page, Integer limit){
        System.out.println("name = " + name);
        System.out.println("msgName = " + msgName);
        System.out.println(service.selectAll2(name, msgName,page,limit));
        return service.selectAll2(name, msgName,page,limit);
    }

    /**实现txt文件的数据导入*/
    @PostMapping("upload.do")
    public R upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //1.验证上传的文件是否为空
        if(file.isEmpty()){
            return R.fail();
        }else {
            //文件有内容
            //2.获取文件名称
            String fn=file.getOriginalFilename();
            //3.获取上传的文件内容
            byte[] data=file.getBytes();
            //4.存储上传的内容到服务器上 输出流
            //存储到发布路径  真实路径
            File f=new File(request.getServletContext().getRealPath("/"),fn);

            FileOutputStream fos=new FileOutputStream(f);
            fos.write(data);
            fos.close();

            return R.ok("http://localhost:8080/"+fn);
        }
    }
    @GetMapping("download.do")
    public void download(HttpServletResponse response) throws IOException {
        service.exportData(response);
    }
}
